library riki_pay;

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:fluwx_pay_only/fluwx_pay_only.dart' as WeChat;
import 'package:tobias/tobias.dart' as AliPay;

export 'package:fluwx_pay_only/fluwx_pay_only.dart';

enum RikiPayType {
  none,
  wechat,
  alipay,
  iap,
}

enum RikiPayStatus {
  success, //成功
  failed, //失败
  cancel, //取消
  waiting, //等待
  uninstall, //未安装
}

class RikiWeChatPayEntity {
  String appId;
  String partnerId;
  String prepayId;
  String packageValue;
  String nonceStr;
  int timeStamp;
  String sign;
  String signType;
  String extData;

  RikiWeChatPayEntity({
    this.appId,
    this.partnerId,
    this.prepayId,
    this.packageValue,
    this.nonceStr,
    this.timeStamp,
    this.sign,
    this.signType,
    this.extData,
  });
}

typedef OnRikiPayCallback = void Function(RikiPayType type, RikiPayStatus status, String message);

class RikiPay {
  // 工厂模式
  factory RikiPay() => _getInstance();

  static RikiPay get instance => _getInstance();
  static RikiPay _instance;

  RikiPay._internal() {
    //初始化
  }

  static RikiPay _getInstance() {
    if (_instance == null) {
      _instance = new RikiPay._internal();
    }
    return _instance;
  }

  String _wechatAppId;
  String _wechatUniversalLink;
  bool _isDebug = false;
  bool _isInit = false; //是否初始化

  void init(String wechatAppId, String wechatUniversalLink, {bool isDebug = false}) {
    if (_isInit) return;
    _isDebug = isDebug;
    _wechatAppId = wechatAppId;
    _wechatUniversalLink = wechatUniversalLink;
    WeChat.registerWxApi(appId: _wechatAppId, universalLink: _wechatUniversalLink);
    _isInit = true;
  }

  void reset() {
    _isInit = false;
  }

  ///是否安装支付宝
  Future<bool> isAliPayInstalled() async {
    return await AliPay.isAliPayInstalled();
  }

  ///是否安装微信
  Future isWeChatInstalled() async {
    return await WeChat.isWeChatInstalled();
  }

  Future<void> pay({@required RikiPayType type, @required OnRikiPayCallback onPay, RikiWeChatPayEntity weChat, String aliPay}) async {
    RikiPayStatus payStatus = RikiPayStatus.failed;
    if (type == RikiPayType.wechat) {
      bool isWechat = await isWeChatInstalled();
      if (!isWechat) {
        onPay(type, RikiPayStatus.uninstall, '请检查是否安装微信！');
        return;
      }
      StreamSubscription<WeChat.WeChatPaymentResponse> _wxPayment;
      _wxPayment = WeChat.responseFromPayment.listen((response) {
//        if (response is WeChat.WeChatPaymentResponse) {
        String msg;
        if (response.errCode == 0) {
          payStatus = RikiPayStatus.success;
          msg = '支付成功';
        } else if (response.errCode == -2) {
          payStatus = RikiPayStatus.cancel;
          msg = '取消支付';
        } else {
          payStatus = RikiPayStatus.failed;
          msg = _isDebug ? response.errStr : '支付失败';
        }
        onPay(type, payStatus, msg);
        _wxPayment?.cancel();
//        }
      });
      Map map = await payWeChat(weChat);
      if (!map["result"]) {
        onPay(type, payStatus, '请检查是否安装微信！');
      }
    } else if (type == RikiPayType.alipay) {
      bool isAliPay = await isAliPayInstalled();
      if (!isAliPay) {
        onPay(type, RikiPayStatus.uninstall, '请检查是否安装支付宝！');
        return;
      }
      Map map = await payAli(aliPay);
      String resultStatus = map["resultStatus"].toString();
      String memo = map["memo"].toString();
      if (resultStatus == "9000") {
        payStatus = RikiPayStatus.success;
        memo = '支付成功';
      } else if (resultStatus == "8000" || resultStatus == "6004") {
        payStatus = RikiPayStatus.waiting;
        memo = '支付完成，等待结果';
      } else if (resultStatus == "6001") {
        payStatus = RikiPayStatus.cancel;
        memo = '取消支付';
      } else {
        payStatus = RikiPayStatus.failed;
        if (_isDebug || memo == null || memo.isEmpty) {
          memo = '支付失败';
        }
      }
      onPay(type, payStatus, memo);
    }
  }

  Future<Map<dynamic, dynamic>> payAli(String aliPay) {
//    {
//      "memo" : "xxxxx",
//    "result" : "{
//    \"alipay_trade_app_pay_response\":{
//    \"code\":\"10000\",
//    \"msg\":\"Success\",
//    \"app_id\":\"2014072300007148\",
//    \"out_trade_no\":\"081622560194853\",
//    \"trade_no\":\"2016081621001004400236957647\",
//    \"total_amount\":\"0.01\",
//    \"seller_id\":\"2088702849871851\",
//    \"charset\":\"utf-8\",
//    \"timestamp\":\"2016-10-11 17:43:36\"
//  },
//    \"sign\":\"NGfStJf3i3ooWBuCDIQSumOpaGBcQz+aoAqyGh3W6EqA/gmyPYwLJ2REFijY9XPTApI9YglZyMw+ZMhd3kb0mh4RAXMrb6mekX4Zu8Nf6geOwIa9kLOnw0IMCjxi4abDIfXhxrXyj********\",
//    \"sign_type\":\"RSA2\"
//  }",
//  "resultStatus" : "9000"
//}
    return AliPay.aliPay(aliPay);
  }

  Future payWeChat(RikiWeChatPayEntity weChat) {
//      {
//        "platform":"Android",//或者iOS
//      result:true //或者false，取决于WXApi.sendRequest()的结果
//      }
    return WeChat.pay(
      appId: weChat.appId,
      partnerId: weChat.partnerId,
      prepayId: weChat.prepayId,
      packageValue: weChat.packageValue,
      nonceStr: weChat.nonceStr,
      timeStamp: weChat.timeStamp,
      sign: weChat.sign,
      signType: weChat.signType,
      extData: weChat.extData,
    );
  }
}
